package com.lj.frame.config.auth;


import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class DecryptFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //过滤URI, 自动续期TOKEN

        //判断是否需要解密
        if (!request.getMethod().equals("POST")){
            //recordLog(request);
            filterChain.doFilter(request, response);
            return;
        }

        String mediaType = request.getContentType();
        if (MediaType.MULTIPART_FORM_DATA_VALUE.equals(mediaType) ||
                ( mediaType!=null && mediaType.startsWith(MediaType.MULTIPART_FORM_DATA_VALUE) ) ){
            recordLog(request);
            filterChain.doFilter(request, response);
            return;
        }

        //判断是否拦截解密
        rewrite(request, response, filterChain);
    }


    private void  recordLog(HttpServletRequest request){
        String method = request.getMethod();
        String url = request.getRequestURI();
        String ip = request.getRemoteAddr();
        String get = request.getQueryString();

        //OperLog operLog = OperLogFactory.buildReuqest(method, url, ip, get, "");
        //operLogService.add(operLog);

        //log.info("recode="+ JSON.toJSONString(operLog));
    }

    private void recordLog(HttpServletRequest request, String body){
        String method = request.getMethod();
        String url = request.getRequestURI();
        String ip = request.getRemoteAddr();
        String get = request.getQueryString();

        //OperLog operLog = OperLogFactory.buildReuqest(method, url, ip, get, body);
        //log.info("recode="+ JSON.toJSONString(operLog));
    }


    /**
     * 错误写出
     *
     * @param response
     * @param msg
     * @param code
     * @throws IOException
     */
    private void writerError(HttpServletResponse response, String msg, int code) throws IOException {
        //验证不通过
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        //将验证不通过的错误返回
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> resultMap = new HashMap<>(3);
        resultMap.put("code", code);
        resultMap.put("msg", msg);
        resultMap.put("data", null);
        response.getWriter().write(mapper.writeValueAsString(resultMap));
    }


    /**
     * 解密重构body
     * */
    private void rewrite(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException {
        DecryptServletRequestWrapper decryptServletRequest = new DecryptServletRequestWrapper(request);
        String s = decryptServletRequest.getBody();
        try{
            String decodeBody = s;// to do 调用解密函数进行解密
            decryptServletRequest.setBody(decodeBody);
            filterChain.doFilter(decryptServletRequest, response);
        }catch (Exception e){
            writerError(response, e.getMessage(), 400);
        }
    }
}
